<script setup>
import MwTable from "./component/MwTablePackage";
import SearchTable from "./component/SearchPackage.vue";
import MwDialog from "@/components/Dialog";
import { ElMessage, ElMessageBox } from 'element-plus';

import { CirclePlus, VideoPlay, UploadFilled, FolderOpened } from '@element-plus/icons-vue';
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue";
import {downloadFile} from '@/utils'
import moment from "moment";

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this

const baseUrl = process.env.VUE_APP_PROXY;
const token = localStorage.getItem('token');

// 生命周期
onMounted(() => {
  getTableData();
  getSelect();
})

const selectVehicle = ref(null);
const selectCamera = ref(null);
let getSelect = () => {
  instance.proxy.$http.get('archiveData.getAmbulanceSelect').then(res=>{
    selectVehicle.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      i['key'] = i.id;
      return i;
    });
  });
  instance.proxy.$http.get('archiveData.getCameraSelect').then(res=>{
    selectCamera.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      i['key'] = i.id;
      return i;
    });
  });
}

// 表格数据
const tableData = ref([]);
const tablLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
});
const searchForm = reactive({});
let getTableData = () => {
  // 查询司机
  let paramsDriver = {
    ...pagination,
    ...searchForm
  };
  tablLoading.value = true;
  instance.proxy.$http.get('overview.version',{ params: paramsDriver }).then(res=>{
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tablLoading.value = false;
  }).catch(err => tablLoading.value = false);
};
function onSearch(){
  getTableData();
};

function onDelete(row){
  ElMessageBox.confirm(
    'Delete Package ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
    }).then(() => {
      instance.proxy.$http.delete('archiveData.deleteFile', {params: {filename: row.fileName}}).then(res=> {});
      instance.proxy.$http.delete('overview.versionDelete', {data: {id: row.id + ''}}).then(res=>{
        onSearch();
        ElMessage({
          type: 'success',
          message: 'Delete Package successfully',
        });
      });
    })
    .catch(() => {});
};


// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' Package');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({
  id: 0,
  isDelete: false,
  size: 0,
  uploadTime: 0,
  packageId: '',
  version: '',
  fileName: '',
  name: '',
})
let fileData = reactive({})
let uploadRef = ref(null);
let dialogRules = reactive({
  packageId: [
    { required: true, message: 'Please input package ID', trigger: 'change' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'change' }, 
  ],
  version: [
    { required: true, message: 'Please input Version Name', trigger: 'change' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'change' }, 
  ],
  fileName: [
    { required: true, message: 'Please input File Name', trigger: 'change' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'change' }, 
  ],
  type: [
    { required: true, message: 'Please input Type', trigger: 'change' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'change' }, 
  ]
});
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = dialogState.value == 'Add' ? 'overview.versionInsert' : 'overview.versionUpdate';
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      } else {
        instance.proxy.$http.put(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      };
    } else {
      console.error('error submit!', fields);
    };
  });
};

let dialogClose = () => {
  dialogShow.value = false;
  dialogRef.value.resetFields();
  for(let item in dialogFrom){
    if(dialogFrom[item] instanceof Array){
      dialogFrom[item] = [];
    }else{
      dialogFrom[item] = '';
    };
  };
  fileData.file = null;
  uploadRef.value.clearFiles();
};

function onEdit(row){
  openDialog('Edit');
  for(let i in row) {
    if (i == 'fileName') {
      let file = {name: row[i], url: window.global_API.prodUrl + 'file/version/' + row[i]};
      fileData.file = file;
      fileData.fileList = [file];
    };
    dialogFrom[i] = row[i];
  };
};

function openDialog(state) {
  dialogState.value = state;
  dialogShow.value = true;
};
function uploadSuccess(res, file, files){
  files.length > 1 && files.shift();
  dialogFrom.fileName = file.name;
  let fileNameList = file?.name?.split('_') || [];
  dialogFrom.version = fileNameList[0] || '';
  dialogFrom.type = fileNameList.some(i => i == 'Software') ? 0 : '';
  
  dialogFrom.size = file.size;
  fileData.file = file;
  fileData.fileList = files;
};
function beforeUpload(file){
  let suffix = file.name.slice(-14, file.name.length);
  if (suffix != '_update.tar.gz') {
    ElMessage({
      type: 'error',
      message: "The upload file suffix must be '_upload. tar. gz'.",
    });
  };
  return suffix == '_update.tar.gz';
};
function fileDownload() {
  if (fileData.file.url) {
    downloadFile(fileData.file, fileData.file.name);
    return;
  };
  downloadFile(fileData.file.raw, fileData.file.raw.name);
};

// ============================ 弹框2 ================================

let dialogShow2 = ref(false);
let dialogTitle2 = ref('Upgrade ');
let dialogState2 = ref('Camera'); //  Camera Vehicle  根据状态来判断提交方法
let submitLoading = ref(false);
let dialogFrom2 = reactive({});
let dialogRow = ref(null);
let type_opction = [
  {label: 'Software', value: 1},
  {label: 'Algorithm', value: 2},
];
let dialogSubmit2 = async () => {
  if(!dialogFrom2?.list.length) {
    ElMessage({
      type: 'error',
      message: 'Please Select',
    });
    return ;
  };
  if (dialogState2.value == 'Camera') {
    ElMessageBox.confirm(
      'Confirm Upgrade ' + dialogState2.value + ' ？',
      'Upgrade ' + dialogState2.value,
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        beforeClose: (action, instances, done) => {
          if (action === 'confirm') {
            instances.confirmButtonLoading = true
            instance.proxy.$http.post('overview.versionUpgrade', {cameraList: dialogFrom2.list, versionId: dialogRow.value.id}).then(res=>{
              instances.confirmButtonLoading = false;
              done();
              if (res.success) {
                ElMessage({
                  type: 'success',
                  message: 'Upgrade message submitted',
                });
                onSearch();
                dialogClose2();
              };
            });
          }
        }
      }).then(() => {
      })
      .catch(() => {});
  }else{
    ElMessageBox.confirm(
      'Confirm Upgrade' + dialogState2.value + ' ？',
      'Upgrade ' + dialogState2.value,
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel'
      }).then(() => {
        instance.proxy.$http.post('overview.versionUpgradeVeh', {ambulanceList: dialogFrom2.list, versionId: dialogRow.value.id}).then(res=>{
          if (res.success) {
            ElMessage({
              type: 'success',
              message: 'Upgrade message submitted',
            });
            onSearch();
            dialogClose2();
          };
        });
      })
      .catch(() => {});
  };
};
let dialogClose2 = () => {
  dialogShow2.value = false;
  dialogFrom2.list = [];
};
function openDialog2(state) {
  dialogState2.value = state;
  dialogShow2.value = true;
};


function upgrade(row, type) {
  dialogRow.value = row;
  if (type == 'camera') {
    openDialog2('Camera');
  }else{
    openDialog2('Vehicle');
  };
};
const filterMethod = (query, item) => item.label.toLowerCase().includes(query.toLowerCase());
</script>
<template>
  <div class="table_index">
    <SearchTable 
      :searchForm="searchForm"
      @onSearch="onSearch"
      @addPeople="openDialog('Add')" />
    <div class="table_content">
      <mw-table
        v-loading="tablLoading"
        :data="tableData"
        :pagination="pagination"
        @paginationChange="onSearch"
        @operate1="onEdit"
        @operate2="(row) => {upgrade(row, 'vehicle')}"
        @operate3="(row) => {upgrade(row, 'camera')}"
        @operate4="onDelete"
      ></mw-table>
    </div>
  </div>

  <mw-dialog
    :show="dialogShow2"
    :title="dialogTitle2 + dialogState2"
    width="900px"
    @submit="dialogSubmit2"
    @close="dialogClose2"
  >
    <el-transfer
      class="transfer_mw"
      v-if="dialogState2 == 'Camera'"
      :titles="['Cameras', 'Target']"
      filterable
      :filter-method="filterMethod"
      v-model="dialogFrom2.list"
      filter-placeholder="State Abbreviations"
      :data="selectCamera"
    />
    <el-transfer
      class="transfer_mw"
      v-else
      :titles="['Vehicles', 'Target']"
      v-model="dialogFrom2.list"
      filterable
      :filter-method="filterMethod"
      filter-placeholder="State Abbreviations"
      :data="selectVehicle"
    />
  </mw-dialog>

  <mw-dialog
    :show="dialogShow"
    :title="dialogState + dialogTitle"
    @submit="dialogSubmit"
    @close="dialogClose"
  >
    <el-form ref="dialogRef" class="dialog_form"  :model="dialogFrom" label-width="170px" :rules="dialogRules">
      <el-form-item label="Package ID"  prop="packageId">
        <el-input v-model="dialogFrom.packageId" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Name">
        <el-input v-model="dialogFrom.name" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Version Number" prop="version">
        <el-input v-model="dialogFrom.version" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Type" prop="type">
        <el-select
          class="value_input" 
          v-model="dialogFrom.type" 
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in type_opction" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Upload Package" prop="fileName">
          <!-- :show-file-list="false" -->
        <el-upload
          class="upload-demo"
          v-model:file-list="fileData.fileList"
          ref="uploadRef"
          accept
          list-type="text"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
          action="/ea-up-ambulance-monitoring/api/camera/version/uploadFile"
          :headers="{token}"
        >
          <el-button>upload</el-button>
          <el-button @click.stop="fileDownload" :disabled="!fileData.file">download</el-button>
        </el-upload>
      </el-form-item>
      <el-alert style="margin-bottom: 12px;" type="warning" title="The upload file suffix must be '_upload. tar. gz'." description="Uploading files requires verification based on the Type value.  Software: ***_Shell__upload.***; Algorithm: ***_Algorithm__upload.***; " :closable="false" />
    </el-form>
  </mw-dialog>
</template>
<style lang="less" scoped>

.transfer_mw{
  --el-transfer-panel-width: 320px;
  --el-transfer-panel-body-height: 500px;
}
// .upload-demo{
//   width: 100%;
// }
.upload-demo{
  width: 100%;
}
.file_card{
  display: flex;
  flex-direction: column;
  padding: 0 15px;
  .el-icon__folder-opened{
    font-size: 65px;
    margin: 20px auto 10px;
  }
  .file_title{
    line-height: 1.4;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }
}
</style>